/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pig.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.admin.api.dto.UserGroupInfo;
import com.pig4cloud.pig.admin.api.dto.UserInfo;
import com.pig4cloud.pig.admin.api.dto.UserItem;
import com.pig4cloud.pig.admin.api.entity.SysDeptGroup;
import com.pig4cloud.pig.admin.api.entity.SysDictItem;
import com.pig4cloud.pig.admin.api.entity.SysUser;
import com.pig4cloud.pig.admin.api.entity.SysUserTenant;
import com.pig4cloud.pig.admin.service.*;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author pigx code generator
 * @date 2021-07-08 13:49:11
 */
@RestController
@AllArgsConstructor
@RequestMapping({"/sysdeptgroup", "/cpsRole/sysdeptgroup"})
@Api(value = "sysdeptgroup", tags = "管理")
public class SysDeptGroupController {

	private final SysDeptGroupService sysDeptGroupService;
	private final SysDictItemService sysDictItemService;
	private final SysUserService sysUserService;
	private final SysUserTenantService sysUserTenantService;
	private final static String COMMA = ",";
	private final String DESIGN_MANAGER_DICT_TYPE = "design_manager";
	private final String DESIGN_DEPT_DICT_TYPE = "design_dept";

	/**
	 * 分页查询
	 *
	 * @param page         分页对象
	 * @param sysDeptGroup
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page")
	public R getSysDeptGroupPage(Page page, SysDeptGroup sysDeptGroup) {
		return R.ok(sysDeptGroupService.page(page, Wrappers.query(sysDeptGroup)));
	}

	/**
	 * 列表查询
	 *
	 * @param deptIdArr     部门ID
	 * @param deptGroupName 组别名称
	 * @return
	 */
	@ApiOperation(value = "列表查询", notes = "列表查询")
	@GetMapping("/list")
	public R getSysDeptGroup(@RequestParam(value = "deptIdArr", required = false) String deptIdArr,
							 @RequestParam(value = "deptGroupName", required = false) String deptGroupName) {
		LambdaQueryWrapper<SysDeptGroup> queryWrapper = new LambdaQueryWrapper<>(SysDeptGroup.class);
		List<Integer> deptIds = StringUtils.isNotBlank(deptIdArr) ? Arrays.stream(deptIdArr.split(COMMA)).map(v -> Integer.parseInt(v)).collect(Collectors.toList()) : null;
		if (CollectionUtils.isNotEmpty(deptIds) && deptIds.size() == 1) {
			queryWrapper.eq(SysDeptGroup::getDeptId, deptIds.get(0));
		} else if (CollectionUtils.isNotEmpty(deptIds) && deptIds.size() > 1) {
			queryWrapper.in(SysDeptGroup::getDeptId, deptIds);
		}
		if (StringUtils.isNotBlank(deptGroupName)) {
			queryWrapper.like(SysDeptGroup::getName, deptGroupName);
		}
		List<SysDeptGroup> sysDeptGroups = sysDeptGroupService.list(queryWrapper);
		return R.ok(sysDeptGroups);
	}

	/**
	 * 通过id查询
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}")
	public R getById(@PathVariable("id") Integer id) {
		return R.ok(sysDeptGroupService.getById(id));
	}

	/**
	 * 新增
	 *
	 * @param sysDeptGroup
	 * @return R
	 */
	@ApiOperation(value = "新增", notes = "新增")
	@SysLog("新增")
	@PostMapping("add")
	/*@PreAuthorize("@pms.hasPermission('test_sysdeptgroup_add')" )*/
	public R save(@RequestBody SysDeptGroup sysDeptGroup) {
		PigUser user = SecurityUtils.getUser();
		if (Objects.isNull(user)) {
			return R.failed("用户未登录");
		}
		if (StringUtils.isBlank(sysDeptGroup.getName())) {
			return R.failed("组别名称不能为空");
		}
		if (Objects.isNull(sysDeptGroup.getDeptId())) {
			return R.failed("部门ID不能为空");
		}
		LambdaQueryWrapper<SysDeptGroup> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.eq(SysDeptGroup::getName, sysDeptGroup.getName());
		queryWrapper.eq(SysDeptGroup::getDeptId, sysDeptGroup.getDeptId());
		int num = sysDeptGroupService.count(queryWrapper);
		if (num > 0) {
			return R.failed(String.format("[%s]组别已存在", sysDeptGroup.getName()));
		}
		sysDeptGroup.setCreateTime(LocalDateTime.now());
		sysDeptGroup.setCreateUserId(user.getId());
		sysDeptGroup.setUpdateTime(LocalDateTime.now());
		sysDeptGroup.setUpdateUserId(user.getId());
		try {
			return R.ok(sysDeptGroupService.save(sysDeptGroup));
		} catch (DuplicateKeyException e) {
			return R.failed(String.format("[%s]组别已存在", sysDeptGroup.getName()));
		}
	}

	/**
	 * 修改
	 *
	 * @param sysDeptGroup
	 * @return R
	 */
	@ApiOperation(value = "修改", notes = "修改")
	@SysLog("修改")
	@PostMapping("/update")
	/* @PreAuthorize("@pms.hasPermission('test_sysdeptgroup_edit')" )*/
	public R updateById(@RequestBody SysDeptGroup sysDeptGroup) {
		PigUser user = SecurityUtils.getUser();
		if (Objects.isNull(user)) {
			return R.failed("用户未登录");
		}
		if (Objects.isNull(sysDeptGroup.getId())) {
			return R.failed("组别ID不能为空");
		}
		if (StringUtils.isBlank(sysDeptGroup.getName())) {
			return R.failed("组别名称不能为空");
		}
		if (Objects.isNull(sysDeptGroup.getDeptId())) {
			return R.failed("部门ID不能为空");
		}
		LambdaQueryWrapper<SysDeptGroup> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.eq(SysDeptGroup::getName, sysDeptGroup.getName());
		queryWrapper.eq(SysDeptGroup::getDeptId, sysDeptGroup.getDeptId());
		queryWrapper.apply("id not in ("+sysDeptGroup.getId()+")");
		int num = sysDeptGroupService.count(queryWrapper);
		if (num > 0) {
			return R.failed(String.format("[%s]组别已存在", sysDeptGroup.getName()));
		}
		try {
			return R.ok(sysDeptGroupService.updateById(sysDeptGroup));
		} catch (DuplicateKeyException e) {
			return R.failed(String.format("[%s]组别已存在", sysDeptGroup.getName()));
		}
	}

	/**
	 * 通过id删除
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除", notes = "通过id删除")
	@SysLog("通过id删除")
	@GetMapping("/del")
	/* @PreAuthorize("@pms.hasPermission('test_sysdeptgroup_del')" )*/
	public R removeById(@RequestParam("id") Integer id) {

		return sysDeptGroupService.remoteDeptGroup(id);
	}


	/**
	 * 根据部门ID获取组别集合
	 * @return
	 */
	@RequestMapping("/getGroupAndUser")
	public R getGroupAndUser(){
		PigUser pigUser = SecurityUtils.getUser();
		SysUser user = sysUserService.getOne(Wrappers.<SysUser>query()
				.lambda().eq(SysUser::getUsername, SecurityUtils.getUser().getUsername()));
		if (user == null) {
			return R.failed(null, String.format("用户信息为空 %s", SecurityUtils.getUser().getUsername()));
		}
		//UserInfo userInfo = sysUserService.findUserInfo(user);
		Boolean isManager = this.isManager();
		List<UserItem> list = new ArrayList<>();
		UserGroupInfo groupInfo = new UserGroupInfo();
		if (isManager) {
			groupInfo.setIsManager(1);
			List<SysDeptGroup> deptGroupList = sysDeptGroupService.list(Wrappers.<SysDeptGroup>lambdaQuery().eq(SysDeptGroup::getDeptId,pigUser.getDeptId()));
			if (CollectionUtils.isNotEmpty(deptGroupList)) {
				List<Integer> groupIds = deptGroupList.stream().map(SysDeptGroup::getId).collect(Collectors.toList());
				// 获取组别下所有的用户
				List<SysUserTenant> sysUserTenantList = sysUserTenantService.list(Wrappers.<SysUserTenant>lambdaQuery()
						.in(SysUserTenant::getDeptGroupId,groupIds)
						.eq(SysUserTenant::getTenantId,pigUser.getTenantId()));
				if (CollectionUtils.isNotEmpty(sysUserTenantList)) {
					Map<Integer,List<SysUserTenant>> groupMap = sysUserTenantList.stream().collect(Collectors.groupingBy(SysUserTenant::getDeptGroupId));
					List<Integer> userIds = sysUserTenantList.stream().map(SysUserTenant::getUserId).collect(Collectors.toList());
					List<SysUser> userList = sysUserService.list(Wrappers.<SysUser>lambdaQuery().in(SysUser::getUserId,userIds));
					Map<Integer,String> userMap = userList.stream().collect(Collectors.toMap(SysUser::getUserId,SysUser::getRealName));

					//构建出参
					deptGroupList.forEach(group -> {
						UserItem item = new UserItem(group.getId(),group.getName());
						List<SysUserTenant> userTenantList = groupMap.get(group.getId());
						//存在组别没有用户的情况
						if (CollectionUtils.isNotEmpty(userTenantList)) {
							List<UserItem> tempUserList = new ArrayList<>();
							userTenantList.forEach(userTenant -> {
								tempUserList.add(new UserItem(userTenant.getUserId(),userMap.get(userTenant.getUserId())));
							});
							item.setUserList(tempUserList);
						}

						list.add(item);
					});

					groupInfo.setList(list);
				}
			}
			return R.ok(groupInfo);
		} else {
			groupInfo.setIsManager(0);
			UserItem item = new UserItem(null,"");
			//非主管获取当前用户所属组别，可以为null
			SysUserTenant userTenant = sysUserTenantService.getOne(Wrappers.<SysUserTenant>lambdaQuery()
					.eq(SysUserTenant::getTenantId,pigUser.getTenantId())
					.eq(SysUserTenant::getUserId,user.getUserId()));
			//设置了组别
			if (userTenant != null && userTenant.getDeptGroupId() != 0) {
				SysDeptGroup deptGroup = sysDeptGroupService.getById(userTenant.getDeptGroupId());
				item = new UserItem(userTenant.getDeptGroupId(),deptGroup.getName());
			}
			List<UserItem> tempUserList = new ArrayList<>();
			tempUserList.add(new UserItem(user.getUserId(),user.getRealName()));
			item.setUserList(tempUserList);

			list.add(item);
			groupInfo.setList(list);
			return R.ok(groupInfo);
		}
	}

	/**
	 * 炎帝--数据图表-获取所有用户(不区分组别)
	 * @return
	 */
	@RequestMapping("/getUserByRoles")
	public R getUserByRoles(){
		PigUser pigUser = SecurityUtils.getUser();
		if (pigUser == null) {
			return R.failed(null, String.format("用户信息为空 %s", SecurityUtils.getUser().getUsername()));
		}
		Boolean isManager = this.isManager();
		List<UserItem> list = new ArrayList<>();
		if (isManager) {
			//获取部门下所有用户
			List<SysUserTenant> sysUserTenantList = sysUserTenantService.list(Wrappers.<SysUserTenant>lambdaQuery().in(SysUserTenant::getDeptId, pigUser.getDeptId()).eq(SysUserTenant::getTenantId, pigUser.getTenantId()));
			if (CollectionUtils.isNotEmpty(sysUserTenantList)) {
				List<Integer> userIds = sysUserTenantList.stream().map(SysUserTenant::getUserId).collect(Collectors.toList());
				List<SysUser> userList = sysUserService.list(Wrappers.<SysUser>lambdaQuery().in(SysUser::getUserId,userIds));
				userList.forEach(info -> list.add(new UserItem(info.getUserId(), info.getRealName())));
			}
//			List<SysDeptGroup> deptGroupList = sysDeptGroupService.list(Wrappers.<SysDeptGroup>lambdaQuery().eq(SysDeptGroup::getDeptId, pigUser.getDeptId()));
//			if (CollectionUtils.isNotEmpty(deptGroupList)) {
//				List<Integer> groupIds = deptGroupList.stream().map(SysDeptGroup::getId).collect(Collectors.toList());
//				// 获取组别下所有的用户
//				List<SysUserTenant> sysUserTenantList = sysUserTenantService.list(Wrappers.<SysUserTenant>lambdaQuery().in(SysUserTenant::getDeptGroupId, groupIds).eq(SysUserTenant::getTenantId, pigUser.getTenantId()));
//				if (CollectionUtils.isNotEmpty(sysUserTenantList)) {
//					List<Integer> userIds = sysUserTenantList.stream().map(SysUserTenant::getUserId).collect(Collectors.toList());
//					List<SysUser> userList = sysUserService.list(Wrappers.<SysUser>lambdaQuery().in(SysUser::getUserId,userIds));
//					userList.forEach(info -> list.add(new UserItem(info.getUserId(), info.getRealName())));
//				}
//			}
		} else {
			SysUser user = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().select(SysUser::getUserId, SysUser::getRealName).eq(SysUser::getUsername, SecurityUtils.getUser().getUsername()));
			list.add(new UserItem(user.getUserId(), user.getRealName()));
		}
		return R.ok(list);
	}
	/**
	 * 炎帝--获取设计部门下所有人
	 * @return
	 */
	@RequestMapping("/getUserByDept")
	public R getUserByDept(){
		PigUser pigUser = SecurityUtils.getUser();
		if (pigUser == null) {
			return R.failed(null, String.format("用户信息为空 %s", SecurityUtils.getUser().getUsername()));
		}
		List<UserItem> list = new ArrayList<>();
		List<SysDictItem> sysDictItemList = sysDictItemService.list(Wrappers.<SysDictItem>query().lambda().eq(SysDictItem::getType, DESIGN_DEPT_DICT_TYPE));
		if (CollectionUtils.isNotEmpty(sysDictItemList)){
			List<String> deptIds = sysDictItemList.stream().map(SysDictItem::getValue).collect(Collectors.toList());
			// 获取组别下所有的用户
			List<SysUserTenant> sysUserTenantList = sysUserTenantService.list(Wrappers.<SysUserTenant>lambdaQuery().in(SysUserTenant::getDeptId, deptIds).eq(SysUserTenant::getTenantId, pigUser.getTenantId()));
			if (CollectionUtils.isNotEmpty(sysUserTenantList)) {
				List<Integer> userIds = sysUserTenantList.stream().map(SysUserTenant::getUserId).collect(Collectors.toList());
				List<SysUser> userList = sysUserService.list(Wrappers.<SysUser>lambdaQuery().in(SysUser::getUserId,userIds));
				userList.forEach(info -> list.add(new UserItem(info.getUserId(), info.getRealName())));
			}

		}
		return R.ok(list);
	}

	/**
	 * 判断当前登录用户是否为设计师主管
	 * @return
	 */
	private Boolean isManager(){
		Boolean result = false;
		//字典表获取设计师主管角色ID
		Integer managerId = -1;
		List<SysDictItem> sysDictItemList = sysDictItemService.list(Wrappers.<SysDictItem>query().lambda().eq(SysDictItem::getType, DESIGN_MANAGER_DICT_TYPE));
		if (CollectionUtils.isNotEmpty(sysDictItemList)) {
			managerId = Integer.parseInt(sysDictItemList.get(0).getValue());
		}
//		Integer[] roles = userInfo.getRoles();
//		List<Integer> list = Arrays.stream(roles).collect(Collectors.toList());
		List<Integer> list = SecurityUtils.getRoles();
		//包含指定角色ID
		if (list.contains(managerId)) {
			result = Boolean.TRUE;
		}
		return result;
	}

}
